var express = require('express');
var fs = require("fs")
var path = require("path");
const app = require('../app');
var router = express.Router();

router.post('/login', function (req, res, next) {
  console.log(req.body);
  fs.readFile(path.resolve("datas", "udata.json"), "utf-8", (err, data)=>{
    if(err){
      return res.send({
        err: true, 
        msg: "读取文件出错"
      })
    }
    let users = JSON.parse(data).users
    for (let key in users) {
      if (users[key].uname == req.body.uname && users[key].upwd == req.body.upwd) {
        // 设置session
        req.session.logined = true
        req.session.uname = req.body.uname
        // 把用户名写入全局变量，每个页面都可以调用
        req.app.locals.userName = req.body.uname;
         return res.send({
          err: false, 
          msg: "登陆成功"
        })
      }
    }
    res.send({
      err: true, 
      msg: "账户名或密码错误"
    })
  })
});

/* GET home page. */
router.get('/', function (req, res) {
  res.render("login")
});

// 退出登录
router.get('/loginout', function (req, res, next) {
  req.session.destroy()
  res.send({
    err: false,
    msg: "退出登录成功"
  })
});


module.exports = router;